package cpu.footprint.ui;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMConversation;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cpu.footprint.R;
import cpu.footprint.adapter.ChatListViewAdapter;
import cpu.footprint.api.ApiUrl;
import cpu.footprint.api.MyApplication;
import cpu.footprint.api.ResultMessage;
import cpu.footprint.bean.BaseBean;
import cpu.footprint.bean.ChatListViewItem;
import cpu.footprint.bean.ChatRecord;
import cpu.footprint.bean.User;
import cpu.footprint.common.BaseActivity;
import cpu.footprint.api.APIService;
import cpu.footprint.api.RespCallBack;
import cpu.footprint.util.CreateDialogUtil;
import cpu.footprint.util.DateUtils;
import cpu.footprint.view.XListView;

/**
 * Created by Administrator on 2017/3/23.
 */
@ContentView(R.layout.activity_talk)
public class TalkActivity extends BaseActivity implements XListView.IXListViewListener {
    @ViewInject(R.id.title_back)
    public ImageView title_back;//点击弹出左侧滑
    @ViewInject(R.id.title_content)
    public TextView title_content;//标题栏内容
    @ViewInject(R.id.title_menu_text)
    public TextView title_menu_text;//标题栏文字功能
    @ViewInject(R.id.title_menu_image)
    public ImageView title_menu_image;//标题栏图形功
    @ViewInject(R.id.title_menu_image2)
    public ImageView title_menu_image2;//标题栏图形功能
    @ViewInject(R.id.edit_content)
    private EditText edit_chatContent;
    @ViewInject(R.id.listview_chat)
    private ListView listViewChat;
    @ViewInject(R.id.listView)
    private XListView listView;
    private ChatListViewAdapter mAdapter;
    private ArrayList<ChatListViewItem> mList;
    private ChatListViewItem item;
    private EMMessageListener msgListener;
    private String chatToName = "";
    private String content = "";
    private ExecutorService pool = null;
    private static String groupId;
    private static int sqlId = 0;
    private String lastRecordId = "0";
    private Dialog mDialog;
    private MyApplication myApplication;
    private User user = new User();
    private boolean isFirstIn = true;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (mDialog != null) {
                if (mDialog.isShowing())
                    mDialog.dismiss();
            }
            switch (msg.what) {
                case ResultMessage.ERROR_MSG: {
                    Toast.makeText(TalkActivity.this, "发送失败！", Toast.LENGTH_SHORT).show();
                }
                break;
                case ResultMessage.SEND_MSG: {
                    edit_chatContent.setText("");
                    item = new ChatListViewItem(ChatListViewItem.ITEM_TYPE.TYPE_RIGHT, content, user.getMobilePhone());
                    mList.add(item);
                    mAdapter.notifyDataSetChanged();
                    listView.setSelection(listView.getBottom());
                    addRecord();
                }
                break;
                case ResultMessage.RECEIVE_MSG: {
                    mAdapter.notifyDataSetChanged();
                    listView.setSelection(listView.getBottom());
                }
                break;
                case ResultMessage.GETLOCAL_MSGS: {
                    mAdapter.notifyDataSetChanged();
                    listView.setSelection(listView.getBottom());
                }
                break;
                default:
                    break;
            }
        }
    };

    /**
     * 添加消息
     */
    private void addRecord() {
        if (content == null || content.isEmpty()) {
            return;
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("mobilePhone", user.getMobilePhone());
        map.put("token", user.getToken());
        map.put("groupId", sqlId + "");
        map.put("content", content);
        map.put("type", 1 + "");//消息类型（1：文字 2：表情 3：语音  4:图片  5:视频）
        map.put("filePath", "");
        APIService.Post(ApiUrl.URL_CHATRECORD_ADD, map, new RespCallBack<BaseBean<ChatRecord>>(this) {
            @Override
            public void onSuccess(BaseBean<ChatRecord> result) {
                super.onSuccess(result);
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }
        });
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        startListener();
        initDataAndView();
        initAdapter();
        requestData("0");
        //创建一个可重用固定线程数的线程池
        pool = Executors.newFixedThreadPool(1);
    }

    private void requestData(String from) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("mobilePhone", user.getMobilePhone());
        map.put("token", user.getToken());
        map.put("groupId", sqlId + "");
        map.put("from", from);
        map.put("pagerCount", 20 + "");
//        mDialog.show();
        APIService.Post(ApiUrl.URL_CHATRECORD_LIST, map, new RespCallBack<BaseBean<ChatRecord>>(this) {
            @Override
            public void onSuccess(BaseBean<ChatRecord> result) {
                super.onSuccess(result);
                if (result.success) {
                    List<ChatRecord> list = result.datas;
                    if (list == null) {
                        list = new ArrayList<ChatRecord>();
                    }
                    System.out.println("------------" + list.toString());
                    for (ChatRecord record : list) {
                        if (user.getMobilePhone().equals(record.getFromUser().getMobilePhone())) {
                            item = new ChatListViewItem(ChatListViewItem.ITEM_TYPE.TYPE_RIGHT, record.getContent(), record.getFromUser().getMobilePhone(), record.getId());
                        } else {
                            item = new ChatListViewItem(ChatListViewItem.ITEM_TYPE.TYPE_LEFT, record.getContent(), record.getFromUser().getMobilePhone(), record.getId());
                        }
                        mList.add(item);
                    }
                    Collections.sort(mList, new Comparator<ChatListViewItem>() {
                        public int compare(ChatListViewItem o1, ChatListViewItem o2) {
                            return o1.getmId().compareTo(o2.getmId());
                        }
                    });
                    for (int i = 0; i < mList.size() - 1; i++) {
                        for (int j = mList.size() - 1; j > i; j--) {
                            if (mList.get(j).getmId() == mList.get(i).getmId()) {
                                mList.remove(j);
                            }
                        }
                    }
                    if (mList.size() > 0)
                        lastRecordId = mList.get(0).getmId() + "";
                    mAdapter.notifyDataSetChanged();
                    if (isFirstIn) {
                        listView.setSelection(listView.getBottom());
                        isFirstIn = false;
                    }else{
                        listView.setSelection(list.size());
                    }
                }
                listView.stopRefresh();
                listView.setRefreshTime(DateUtils.dateToString(new Date()));
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }

            @Override
            public void onFinished() {
                super.onFinished();
                mDialog.dismiss();
            }
        });
    }

    private void initDataAndView() {
        title_back.setImageResource(R.mipmap.back);
        title_menu_text.setVisibility(View.GONE);
        title_menu_image.setVisibility(View.GONE);
        title_menu_image2.setVisibility(View.VISIBLE);
        title_menu_image2.setImageResource(R.mipmap.groupinfo);
        listView.setPullLoadEnable(false);
        listView.setPullRefreshEnable(true);
        listView.setXListViewListener(this);
        chatToName = this.getIntent().getStringExtra("chatToName");
        groupId = this.getIntent().getStringExtra("groupId");
        sqlId = this.getIntent().getIntExtra("sqlId", 0);
        title_content.setText(chatToName);
        mList = new ArrayList<>();
        mDialog = CreateDialogUtil.CreateDialog(this, "请稍后...", mHandler);
        myApplication = (MyApplication) TalkActivity.this.getApplication();
        if (!myApplication.isLogin() || myApplication.getUser() == null) {
            Toast.makeText(TalkActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(TalkActivity.this, LoginActivity.class);
            intent.putExtra("IsLogin", false);
            startActivity(intent);
            overridePendingTransition(0, R.anim.fade);
            TalkActivity.this.finish();
        } else {
            user = myApplication.getUser();
        }
    }

    @Event(value = {R.id.btn_send, R.id.title_back, R.id.title_menu_image2})
    private void OnClick(View v) {
        switch (v.getId()) {
            case R.id.btn_send: {
                content = edit_chatContent.getText().toString().trim();
                if (!content.equals("")) {
                    sendNews();
                }
            }
            break;
            case R.id.title_back: {
                TalkActivity.this.finish();
                overridePendingTransition(0, R.anim.fade);
            }
            break;
            case R.id.title_menu_image2: {
                //TalkActivity.this.finish();
                Intent intent = new Intent(this, GroupInfoActivity.class);
                intent.putExtra("groupId", groupId);
                intent.putExtra("sqlId", sqlId);
                startActivityForResult(intent, 1);
                overridePendingTransition(0, R.anim.fade);
            }
            break;
        }
    }

    /**
     * 初始化消息适配器
     */
    private void initAdapter() {
        mAdapter = new ChatListViewAdapter(TalkActivity.this, mList, listView);
        listView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
    }

    private void sendNews() {
//        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
//        boolean isOpen=imm.isActive();//isOpen若返回true，则表示输入法打开
//        imm.showSoftInput(edit_chatContent, InputMethodManager.SHOW_FORCED);
        pool.execute(CreateSendThread(content, groupId));
        edit_chatContent.requestFocus();
    }

    private void startListener() {
        msgListener = new EMMessageListener() {
            @Override
            public void onMessageReceived(final List<EMMessage> messages) {
                //收到消息
                for (int i = 0; i < messages.size(); i++) {
                    String content = messages.get(i).getBody().toString();
                    //list.add(content);
                    content = content.replace("txt:", "");
                    content = content.replace("\"", "");
                    if (!content.equals(item.getContent())) {
                        item = new ChatListViewItem(ChatListViewItem.ITEM_TYPE.TYPE_LEFT, content, messages.get(i).getFrom());
                        mList.add(item);
                    }
                }
                mHandler.sendEmptyMessage(ResultMessage.RECEIVE_MSG);
            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> messages) {
                //收到透传消息
            }

            @Override
            public void onMessageRead(List<EMMessage> messages) {
                //收到已读回执
            }

            @Override
            public void onMessageDelivered(List<EMMessage> message) {
                //收到已送达回执
            }

            @Override
            public void onMessageChanged(EMMessage message, Object change) {
                //消息状态变动
            }
        };
        EMClient.getInstance().chatManager().addMessageListener(msgListener);
    }

    @Override
    protected void onResume() {
        startListener();
        EMClient.getInstance().chatManager().loadAllConversations();
        //   getMessages().start();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        //记得在不需要的时候移除listener，如在activity的onDestroy()时
        if (msgListener != null)
            EMClient.getInstance().chatManager().removeMessageListener(msgListener);
        if (pool != null) {
            pool.shutdownNow();
        }
        super.onDestroy();
    }

    /**
     * 获取聊天记录
     *
     * @return
     */
    private Thread getMessages() {
        Thread messageThread = new Thread(new Runnable() {
            @Override
            public void run() {
                EMConversation conversation = EMClient.getInstance().chatManager().getConversation(groupId);
                //获取此会话的所有消息
                if (conversation == null)
                    return;
                List<EMMessage> message = conversation.getAllMessages();
                //获取startMsgId之前的pageSize条消息，此方法获取的messages SDK会自动存入到此会话中，APP中无需再次把获取到的messages添加到会话中
                if (message == null || message.size() < 1)
                    return;
                String startMsgId = message.get(0).getMsgId();
                List<EMMessage> messages = conversation.loadMoreMsgFromDB(startMsgId, 20);
                List<EMMessage> messageList = new ArrayList<EMMessage>();
                if (messages.size() < message.size()) {
                    messageList.addAll(message);
                } else {
                    messageList.addAll(messages);
                }
                for (int i = 0; i < messageList.size(); i++) {
                    String content = messageList.get(i).getBody().toString();
                    content = content.replace("txt:", "");
                    content = content.replace("\"", "");
                    if (messageList.get(i).getFrom().equals(user.getMobilePhone())) {
                        item = new ChatListViewItem(ChatListViewItem.ITEM_TYPE.TYPE_RIGHT, content, messageList.get(i).getFrom());
                    } else {
                        item = new ChatListViewItem(ChatListViewItem.ITEM_TYPE.TYPE_LEFT, content, messageList.get(i).getFrom());
                        //         item = new ChatListViewItem(ChatListViewItem.ITEM_TYPE.TYPE_RIGHT, content,messages.get(i).getFrom());
                    }
                    mList.add(item);
                }
                mHandler.sendEmptyMessage(ResultMessage.GETLOCAL_MSGS);
            }
        });
        return messageThread;
    }

    private Thread CreateSendThread(String text, String id) {
        final String talkContent = text;
        final String groupid = id;
        Thread thread = null;
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //创建一条文本消息，content为消息文字内容，toChatUsername为对方用户或者群聊的id，后文皆是如此
                    EMMessage message = EMMessage.createTxtSendMessage(talkContent, groupid);
                    //如果是群聊，设置chattype，默认是单聊
                    message.setChatType(EMMessage.ChatType.GroupChat);
                    //发送消息
                    EMClient.getInstance().chatManager().sendMessage(message);
                    mHandler.sendEmptyMessage(ResultMessage.SEND_MSG);
                } catch (Exception e) {
                    e.printStackTrace();
                    mHandler.sendEmptyMessage(ResultMessage.ERROR_MSG);
                }
            }
        });
        return thread;
    }

    /**
     * 重写后退函数
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            TalkActivity.this.finish();
            overridePendingTransition(0, R.anim.fade);
            return true;
        } else
            return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onRefresh() {
        requestData(lastRecordId);
    }

    @Override
    public void onLoadMore() {

    }
}
